package com.edfu.core.commons.persistence.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import com.edfu.core.commons.persistence.api.IInterestsMgtPersistence;
import com.edfu.core.commons.persistence.entity.CategoryEntity;
import com.edfu.core.commons.persistence.entity.InterestsEntity;
import com.edfu.core.identitymgt.persistence.entity.UserEntity;

@Repository
public class InterestsMgtPersistenceImpl implements IInterestsMgtPersistence {
	
	private static Logger logger = LoggerFactory.getLogger(InterestsMgtPersistenceImpl.class);
	
	private EntityManager entityManager;
	
	@PersistenceContext
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	@Override
	public InterestsEntity addInterests(UserEntity ue, CategoryEntity cce) {
		logger.debug("Adding interests for the user " + ue.getUserId());
		InterestsEntity ie = new InterestsEntity();
		ie.setCategory(cce);
		ie.setUser(ue);
		
		return entityManager.merge(ie);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<InterestsEntity> getUserInterests(UserEntity user) {
		Query query  = entityManager.createQuery("select i from InterestsEntity i where i.user = :user");
		query.setParameter("user", user);
		
		return query.getResultList();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<InterestsEntity> getCategoryInterests(CategoryEntity category) {
		Query query  = entityManager.createQuery("select i from InterestsEntity i where i.category = :category");
		query.setParameter("category", category);
		
		return query.getResultList();
	}			

}
